package com.ctgu.rabbitmq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.rabbitmq.entity.OrdersEntity;
import com.ctgu.rabbitmq.mapper.OrdersMapper;
import com.ctgu.rabbitmq.rabbitmq.exchange.orderDemo.RabbitMQPaymentConfig;
import com.ctgu.rabbitmq.service.OrdersService;
import com.ctgu.rabbitmq.utils.ApiResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
* @author Alex2
* @description 针对表【t_orders】的数据库操作Service实现
* @createDate 2025-03-07 15:02:03
*/
@Log4j2
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersEntity>
    implements OrdersService {

    private final RabbitTemplate rabbitTemplate;

    private static final String TAG = "Alex";

    public OrdersServiceImpl(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * @ Author: Alex
     * @ Description: 实战案例-购物增加积分-插入订单
     */
    @Override
    public ApiResult insertOrder(String name, BigDecimal price, Integer userId) {
        OrdersEntity orders = lambdaQuery().eq(OrdersEntity::getName, name).one();
        if (orders != null) {
            return ApiResult.error("该商品已存在");
        }
        OrdersEntity ordersEntity = new OrdersEntity(null, name, price, userId, "UNPAID", LocalDateTime.now());
        boolean save = save(ordersEntity);
        if (save) {
            return ApiResult.success("插入订单成功", ordersEntity);
        } else {
            return ApiResult.error("插入订单失败");
        }
    }

    /**
     * @ Author: Alex
     * @ Description: 实战案例-购物增加积分-消费增加积分
     */
    @Override
    public ApiResult payment(String id) {
        OrdersEntity orders = lambdaQuery().eq(OrdersEntity::getId, id).one();
        if (orders == null) {
            return ApiResult.error("订单不存在");
        }
        rabbitTemplate.convertAndSend("", RabbitMQPaymentConfig.PAYMENT_QUEUE, orders);
        log.debug("{} : 消息已发送 : {}", TAG, orders);
        return ApiResult.success("付款成功");
    }
}